package com.example.tasks

import java.io.File
import java.util.regex.Pattern
import java.util.zip.CRC32

fun main() {
    val path = "F:\\ToolsSources"
//    removeWindowsReduceName(path)
    removeSameContent(path)
}

private fun removeWindowsReduceName(path: String) {
    //Groove Coverage - Far Away from Home(2).mp3
    val compile = Pattern.compile("\\(\\d\\)\\.mp3")
    File(path).listFiles { file, s ->
        File(file, s).isFile
    }.filter {
        compile.matcher(it.name).find()
    }.forEach {
        println(it.name)
        it.delete()
    }
}

private fun removeSameContent(path: String) {
    File(path).listFiles { file, s ->
        File(file, s).isFile
    }.groupBy {
        crc32(it)
    }.forEach { entry ->
        if (entry.value.size > 1) {
            entry.value.forEachIndexed { index, file ->
                if (index >= 1) {
                    println("delete ${file.absolutePath}")
                    file.delete()
                }
            }
             
        }
    }
}

fun crc32(file: File): String {
    val crc32 = CRC32()
    file.inputStream().use { inputStream ->
        val buffer = ByteArray(8 * 1024)
        var len: Int
        while ((inputStream.read(buffer)).also { len = it } != -1) {
            crc32.update(buffer, 0, len)
        }
    }
    return java.lang.Long.toHexString(crc32.value)
}